<?php

class MenuController extends AdminController {

    const MODEL_CLASS_NAME = 'Menu';

    //TODO :Comment by Kien.Tran
//    const RENDER = 0;
//    // The action will publish loaded model.
//    const PROCEED = 1;
//    // The action will cancel the publish.
//    const CANCEL = 2;

    /**
     * @var boolean is this an AJAX request.
     */
    protected $isAjaxRequest;

    /**
     * @var string scripts which should be disabled on AJAX call.
     */
    public $disableScripts = array();

    public function actionIndex($id = null) {

	if (isset($id)) {
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, null);
	    $arr = array();
	    $arr['menu_type_id'] = $id;
	    
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $arr);
	    $this->redirect(url($this->id));
	    app()->end();
		    
	}

	$model = new Menu('search');
	$model->unsetAttributes();  // clear any default values
	if (isset($_GET[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_GET[self::MODEL_CLASS_NAME];

	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_GET[self::MODEL_CLASS_NAME]);
	} else if (isset($_POST[self::MODEL_CLASS_NAME])) {
	    $model->attributes = $_POST[self::MODEL_CLASS_NAME];
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, $_POST[self::MODEL_CLASS_NAME]);
	} else {
	    $stateMenu = Yii::app()->user->getState(app()->controller->id . self::MODEL_CLASS_NAME);
	    if ($stateMenu != null)
		$model->attributes = $stateMenu;
	}

	if (!isset($model->menu_type_id)) {
	   $model->menu_type_id = MenuType::model()->find()->id;
	}
	
	$menuType = MenuType::model()->findByPk($model->menu_type_id);

	if ($menuType == NULL) {
	    throw new CHttpException(404, t(404, 'messages'));
	}
	$this->render('index', array('model' => $model));
    }

    /**
     * Remove all search information of Menu model except menu_type_id
     */
    public function actionRefresh() {
	$stateMenu = Yii::app()->user->getState(app()->controller->id . self::MODEL_CLASS_NAME);

	if (isset($stateMenu) && isset($stateMenu['menu_type_id'])) {
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, array('menu_type_id' => $stateMenu['menu_type_id']));
	} else {
	    Yii::app()->user->setState(app()->controller->id . self::MODEL_CLASS_NAME, null);
	}
	$this->redirect(url(app()->controller->id . "/index"));
    }

    function actions() {
	return array(
	    'create' => array(
		'class' => 'lib.components.actions.CreateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'messages' => array('success' => t('MSG_INFO_INSERT_SUCCESS', 'messages', array('{0}' => t('LBL_MENU_ITEM', 'menu'))))
	    ),
	    'update' => array(
		'class' => 'lib.components.actions.UpdateAction',
		'modelClass' => self::MODEL_CLASS_NAME,
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_MENU_ITEM', 'menu'))))
	    ),
	    'delete' => array(
		'class' => 'lib.components.actions.DeleteAction',
		'customAction' => 'deleteMenu',
		'ajaxView' => "//share/_delete",
		'messages' => array('success' => t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_MENU_ITEM', 'menu'))))
	    ),
	    'setdefaultpage' => array(
		'class' => 'lib.components.actions.LGUpdateAnItemAction',
		'customAction' => 'defaultPage',
		'modelClass' => self::MODEL_CLASS_NAME,
		'itemName' => t('LBL_MENU_ITEM', 'menu'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_MENU_ITEM', 'menu'))))
	    ),
	    'active' => array(
		'class' => 'lib.components.actions.LGActiveItemAction',
		'customAction' => 'activeMenuItem',
		'modelClass' => self::MODEL_CLASS_NAME,
		'itemName' => t('LBL_MENU_ITEM', 'menu'),
		'messages' => array('success' => t('MSG_INFO_UPDATE_SUCCESS', 'messages', array('{0}' => t('LBL_MENU_ITEM', 'menu'))))
	    ),
	);
    }

//    public function validateMenu ($method) {
//	
//	return NULL;
//    }

    /*
     * Ajax get data when changing extension
     */

    public function actionGetExtensionView() {
	if (Yii::app()->request->isAjaxRequest && isset($_GET['id'])) {
	    $id = $_GET['id'];

	    $extension = Extension::model()->find('id=?', array($id));
	    if ($extension) {
		$params = null;
		if (isset($_GET['param'])) {
		    $params = CJSON::decode($_GET['param']);
		}
		$link = $extension->controller . "/" . $extension->action;
		$alias = $_GET['alias'];
		if ($params['id'] != null)
		    $link = $link . "/" . $params['id'] . $alias;
		$link = str_replace(Yii::app()->baseUrl, '', $link);

		$arr = array('view' => $extension->view, 'link' => $link);
		echo CJSON::encode($arr);
	    }
	}
    }

    private function disableScripts() {
	// Disable scripts
	if (Yii::app()->request->isAjaxRequest) {
	    $defaultDisableScripts = array(
		'jquery.js',
		'jquery.min.js',
		'jquery-ui.min.js',
	    );
	    foreach ($defaultDisableScripts as $script)
		Yii::app()->clientScript->scriptMap[$script] = false;
	}
    }

//    public function stopJS() {
//	$defaultDisableScripts = array(
//	    'jquery.js',
//	    'jquery.min.js',
//	    'jquery-ui.min.js',
//	);
//
//	// Merge with user set scripts which should be disabled
//	if (is_array($this->disableScripts)) {
//	    $this->disableScripts = CMap::mergeArray(
//			    $defaultDisableScripts, $this->disableScripts);
//	}
//	else
//	    throw new CException(Yii::t($this->tCategory, t('MSG_DISABLE_SCRIPT', 'messages')));
//
//	// Disable scripts
//	foreach ($this->disableScripts as $script)
//	    Yii::app()->clientScript->scriptMap[$script] = false;
//    }

    public function actionSelectArticle() {
	$this->disableScripts();

	$model = new Article("search");
	$model->unsetAttributes();  // clear any default values
	$model->status = LGConstant::PUBLISH_STATUS;
	
	if (isset($_GET['Article']))
	    $model->attributes = $_GET['Article'];

	if (Yii::app()->request->isAjaxRequest) {
	    // Output JSON encoded content
	    echo CJSON::encode(array(
		'status' => 'render',
		'content' => $this->renderPartial('selectArticle', array('model' => $model), true, true),
	    ));
	    Yii::app()->end();
	} else {
	    $this->render('selectArticle', array(
		'model' => $model
	    ));
	}
    }

    public function loadModel() {
	$model = null;
	if (isset($_GET['id'])) {
	    $ids = explode(',', $_GET['id']);
	    if (isset($ids)) {
		$criteria = new CDbCriteria;
		$criteria->addInCondition('id', $ids);
		$model = Menu::model()->findAll($criteria);
	    }
	}
	return $model;
    }

//    public function actionActive($id) {
//	if (Yii::app()->request->isAjaxRequest) {
//	    if ($id != '') {
//		$menu = Menu::model()->findByPk($id);
//		$menu->status = ($menu->status == 1 ? 0 : 1);
//		$menu->saveAttributes(array('status'));
//		echo CJSON::encode(array(
//		    'status' => 'success',
//		    'content' => Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => 'Menu', '{1}' => 'actived'))
//		));
//		app()->end();
//	    }
//	}
//    }
// TODO: Comment by Kien.Tran
//    public function actionActive($id) {
//	if (Yii::app()->request->isAjaxRequest && ($id != '')) {
//	    $menu = Menu::model()->findByPk($id);
//	    $menu->scenario = Menu::SCENARIO_UPDATE;
//
//	    $newStatus = null;
//	    if ($menu->status == LGConstant::PUBLISH_STATUS) {
//		$newStatus = LGConstant::UNPUBLISH_STATUS;
//		$msgStatus = t('LBL_INACTIVED', 'menu');
//	    } else {
//		$newStatus = LGConstant::PUBLISH_STATUS;
//		$msgStatus = t('LBL_ACTIVED', 'menu');
//	    }
//
//	    $isSuccess = $menu->changeStatus($newStatus);
//
//	    if ($isSuccess) {
//		echo CJSON::encode(array(
//		    'status' => MsgType::SUCCESS,
//		    'content' => Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => t('LBL_MENU', 'menu'), '{1}' => $msgStatus))
//		));
//	    } else {
//		if ($menu->getError('status') != null) {
//		    $msg = $menu->getError('status');
//		} else {
//		    $msg = Yii::t('messages', 'MSG_NOT_ACTIVATED', array('{0}' => t('LBL_MENU', 'menu'), '{1}' => $msgStatus));
//		}
//
//		echo CJSON::encode(array(
//		    'status' => MsgType::ERROR,
//		    'content' => $msg)
//		);
//	    }
//	    app()->end();
//	}
//    }

    public function actionLoadParentID($id, $menuTypeID) {
	$arrEmpty = array('0' => t('MSG_NO_PARENT', 'messages'));
	
	$arr = Menu::model()->getParentId($id, $menuTypeID);
	$arr = array_merge($arrEmpty, $arr);
	echo json_encode($arr);
    }
    
    public function activeMenuItem($models, $action) {
	$msgReturn = null;
	if ($models != null && !empty($models)) {
	    $menu = $models[0];
	    $menu->scenario = Menu::SCENARIO_UPDATE;

	    $newStatus = null;
	    if ($menu->status == LGConstant::PUBLISH_STATUS) {
		$newStatus = LGConstant::UNPUBLISH_STATUS;
		$msgStatus = t('LBL_INACTIVED', 'menu');
	    } else {
		$newStatus = LGConstant::PUBLISH_STATUS;
		$msgStatus = t('LBL_ACTIVED', 'menu');
	    }

	    $isSuccess = $menu->changeStatus($newStatus);

	    if ($isSuccess) {
		$msgReturn = new LGMessage(
			MsgType::SUCCESS, Yii::t('messages', 'MSG_INFO_SUCCESS', array('{0}' => t('LBL_MENU_ITEM', 'menu'), '{1}' => $msgStatus))
		);
	    } else {
		if ($menu->getError('status') != null) {
		    $msg = $menu->getError('status');
		} else {
		    $msg = Yii::t('messages', 'MSG_NOT_ACTIVATED', array('{0}' => t('LBL_MENU_ITEM', 'menu'), '{1}' => $msgStatus));
		}

		$msgReturn = new LGMessage(
			MsgType::ERROR, $msg);
	    }
	} else {
	    $msgReturn = new LGMessage(
		    sgType::ERROR, $action->messages['error']);
	}
	return $msgReturn;
    }

// TODO: Comment by Kien.Tran
//    public function actionSetDefaultPage($id) {
//	if (Yii::app()->request->isAjaxRequest) {
//	    if ($id != '') {
//		$menu = Menu::model()->findByPk($id);
//		if ($menu) {
//		    Menu::model()->updateAll(array('default_page' => LGConstant::DEFAULT_PAGE_NO), '');
//
//		    $menu->default_page = LGConstant::DEFAULT_PAGE_YES;
//		    $menu->saveAttributes(array('default_page'));
//		    echo CJSON::encode(array(
//			'status' => MsgType::SUCCESS,
//			'content' => Yii::t('messages', 'MSG_SET_DEFAULT_PAGE_SUCCESS')
//		    ));
//		    app()->end();
//		}
//	    }
//	}
//    }

    /**
     * @author Kien Tran <kien.tran@logigear.com>
     * @param type $models
     * @param type $action
     * @return \LGMessage
     */
    public function defaultPage($models, $action) {
	$model = $models[0];
	$model->scenario = 'update';

	$msgReturn = NULL;
	$isSuccessful = false;
	if (isset($model)) {

	    $menu = $model;
	    Menu::model()->updateAll(array('default_page' => LGConstant::DEFAULT_PAGE_NO), '');

	    $menu->default_page = LGConstant::DEFAULT_PAGE_YES;
	    $isSuccessful = $menu->saveAttributes(array('default_page'));

	    if ($isSuccessful) {
		$msg = Yii::t('messages', 'MSG_SET_DEFAULT_PAGE_SUCCESS');
		$msgReturn = new LGMessage(MsgType::SUCCESS, $msg);
	    } else {
		$msgReturn = new LGMessage(MsgType::ERROR, $action->messages['error']);
	    }
	} else {
	    $msgReturn = new LGMessage(MsgType::ERROR, $action->messages['error']);
	}

	return $msgReturn;
    }

//    public function actionOrder($id, $order, $action) {
//	if (Yii::app()->request->isAjaxRequest) {
//	    $menu = new Menu("order");
//	    if (strstr($action, LGConstant::ACTION_DOWN)) {
//		$menu_up = $menu->model()->findByPk($id);
//		$menu_up->display_order = (int) $order + 1;
//
//		$menu_down = $menu->searchByDisplayOrder((int) $order + 1, $menu_up->parent_id);
//		$menu_down->display_order = $order;
//
//		$menu_down->saveAttributes(array('display_order'));
//		$menu_up->saveAttributes(array('display_order'));
//	    } else {
//		$menu_up = $menu->model()->findByPk($id);
//		$menu_up->display_order = (int) $order - 1;
//
//		$menu_down = $menu->searchByDisplayOrder((int) $order - 1, $menu_up->parent_id);
//		$menu_down->display_order = $order;
//
//
//		$menu_down->saveAttributes(array('display_order'));
//		$menu_up->saveAttributes(array('display_order'));
//	    }
//	}
//    }

    /**
     * Swape 2 menu item. The items must be same parent_id together.
     * @param type $id
     * @param type $action
     * @throws InvalidArgumentException
     * @throws CHttpException
     * @author Kien Tran <kien.tran@logigear.com>
     */
    public function actionOrder($id, $action) {

      if ($id == NULL || $action == NULL) {
         throw new InvalidArgumentException();
      } else {
         $menuFrom = Menu::model()->findByPk($id);
         $menuTo =  Menu::model()->findByPk($action);
         if ($menuFrom == NULL || $menuTo == NULL) {
            throw new CHttpException(404, Yii::t('messages', '404'));
         }

         //Check Are parent ids like together?
         if ($menuFrom->parent_id != $menuTo->parent_id) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }
         $temp = $menuFrom->display_order;
         $menuFrom->display_order = $menuTo->display_order;
         $menuTo->display_order = $temp;

         if (!$menuFrom->saveAttributes(array('display_order'))) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }

         if (!$menuTo->saveAttributes(array('display_order'))) {
            throw new CHttpException(500, Yii::t('messages', '500'));
         }
      }
   }
   
    /**
     * Custumize delete action for delete menu tree
     * @param array $model menu array
     * @return \LGMessage
     * @author Kien Tran <kien.tran@logigear.com>
     */
    public function deleteMenu($model) {
	$isDeleted = true;
	$transaction = Menu::model()->dbConnection->beginTransaction();
	for ($i = 0; $i < count($model); $i++) {
	    $m = $model[$i];

	    //Get all children of the $m node
	    //And check the children with $model items
	    //It is equal, remove 
	    $list_child_menu = Menu::model()->getAllNodesHaveRootSpecifiedID($m->id);

	    foreach ($list_child_menu as $data) {

		//check the children with $model items
		//It is equal, remove 
		for ($j = $i; $j < count($model); $j++) {
		    $c = $model[$j];
		    if ($data->id == $c->id) {
			array_splice($model, $j, 1);
		    }
		}

		$menu = new Menu();
		$menu->deleteByPk($data['id']);
	    }

	    $isDeleted = $m->delete();
	    if ($isDeleted == false)
		break;
	}

	// The model deleted successfully
	if ($isDeleted) {
	    $transaction->commit();
	    $msg = new LGMessage(MsgType::SUCCESS, t('MSG_INFO_DELETE_SUCCESS', 'messages', array('{0}' => t('LBL_MENU', 'menu'))));

	    return $msg;
	}

	// Deletion was unsuccessful, set flash message
	else {
	    $transaction->rollback();
	    $msg = new LGMessage(MsgType::SUCCESS, t('THERE_WAS_AN_ERROR_WHILE_DELETING._PLEASE_TRY_AGAIN.', 'messages'));
	    return $msg;
	}
    }
    
     public function getMenuDisplayName($menu) {
      if ($menu != NULL) {
         $html = str_repeat('|---', $menu->level);
	 $html = '<span class="indent">'.$html.'</span>';
         $url = $this->createUrl("update", array("id" => $menu->id));
         $nameTag = CHtml::link(CHtml::encode($menu->title), $url);
         $html .= $nameTag;

         return $html;
      }
      return '';
   }
   
   public function getHtmlUpButtonOfProductImage($menu) {

      $html = '';
      if ($menu->isUp != NULL) {
         $actionParam = '?action=' . $menu->isUp;
         $actionClassName = 'icon ' . LGConstant::ACTION_UP;

         $url = url(app()->controller->id . '/order/' . $menu->id . $actionParam);
	 $html .= $this->createAjaxButtonUpdateGridView( $actionClassName, $url);
      } else {
         $actionClassName = 'icon ' . LGConstant::ACTION_UP . ' disable';
         $html .= CHtml::button('', array(
                     'class' => $actionClassName,
         ));
      }

      return $html;
   }

   public function createAjaxButtonUpdateGridView ($className, $url) {
      return '<input class="'.$className.'" onclick="LGCMS.ajaxCallback(\''.$url.'\')" name="yt2" type="button">';
   }
   public function getHtmlDownButtonOfProductImage($menu) {
      $html = '';
      if ($menu->isDown != NULL) {
         $actionParam = '?action=' . $menu->isDown;
         $actionClassName = 'icon ' . LGConstant::ACTION_DOWN;

	 $url = url( '/'.app()->controller->id . '/order/' . $menu->id . $actionParam);
         $html .= $this->createAjaxButtonUpdateGridView( $actionClassName,$url);
      } else {
         $actionClassName = 'icon ' . LGConstant::ACTION_DOWN . ' disable';
         $html .= CHtml::button('', array(
                     'class' => $actionClassName,
         ));
      }

      return $html;
   }

    /* public function actionPublish() {
      $this->disableScripts();
      // Get the model
      $model = $this->loadModel();

      // Get the action status
      $actionStatus = self::RENDER;
      if (isset($_POST['Confirmed']))
      $actionStatus = self::PROCEED;
      else if (isset($_POST['Canceled']))
      $actionStatus = self::CANCEL;

      // Delete is confirmed, proceed
      if ($actionStatus === self::PROCEED) {
      $isPublish = true;
      foreach ($model as $m) {
      $isPublish = $m->publish();
      if ($isPublish == false)
      break;
      }
      // The model published successfully
      if ($isPublish) {
      // Accessing through AJAX, return success content

      if (Yii::app()->request->isAjaxRequest) {
      // Output JSON encoded content
      echo CJSON::encode(array(
      'status' => MsgType::SUCCESS,
      'content' => t('MSG_INFO_SUCCESS', 'messages', array('{0}' => 'Menu', '{1}' => 'published')),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      }
      // Deletion was unsuccessful, set flash message
      else
      echo CJSON::encode(array(
      'status' => 'error',
      'content' => t('MSG_INFO_ERROR', 'messages', array('{0}' => 'Menu', '{1}' => 'published')),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      // Render delete page using AJAX
      if (Yii::app()->request->isAjaxRequest) {
      // Output JSON encoded content
      echo CJSON::encode(array(
      'status' => 'render',
      'content' => $this->renderPartial("//menu/_common", array(
      'model' => $model), true, true),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      }
     */

    /* public function actionUnpublish() {
      $this->disableScripts();
      // Get the model
      $model = $this->loadModel();

      // Get the action status
      $actionStatus = self::RENDER;
      if (isset($_POST['Confirmed']))
      $actionStatus = self::PROCEED;
      else if (isset($_POST['Canceled']))
      $actionStatus = self::CANCEL;

      // Delete is confirmed, proceed
      if ($actionStatus === self::PROCEED) {
      $isUnpublish = true;
      foreach ($model as $m) {
      $isUnpublish = $m->unpublish();
      if ($isUnpublish == false)
      break;
      }
      // The model published successfully
      if ($isUnpublish) {
      // Accessing through AJAX, return success content

      if (Yii::app()->request->isAjaxRequest) {
      // Output JSON encoded content
      echo CJSON::encode(array(
      'status' => MsgType::SUCCESS,
      'content' => t('MSG_INFO_SUCCESS', 'messages', array('{0}' => 'Menu', '{1}' => 'unpublished')),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      }
      // Deletion was unsuccessful, set flash message
      else
      echo CJSON::encode(array(
      'status' => 'error',
      'content' => t('MSG_INFO_ERROR', 'messages', array('{0}' => 'Menu', '{1}' => 'unpublished')),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      // Render delete page using AJAX
      if (Yii::app()->request->isAjaxRequest) {
      // Output JSON encoded content
      echo CJSON::encode(array(
      'status' => 'render',
      'content' => $this->renderPartial("//menu/_common", array(
      'model' => $model), true, true),
      ));
      // Stop script execution
      Yii::app()->end();
      }
      }
     */
}

?>